﻿using Abp.Application.Services.Dto;
using Abp.Domain.Repositories;
using Batman.Cms.Controllers.Weixins.Input;
using Batman.Cms.Core.Models.Mvc;
using Batman.Cms.Core.Services;
using Batman.Cms.Core.Tools;
using Batman.Cms.Domains;
using Batman.Cms.DomainServices;
using Microsoft.EntityFrameworkCore;
using System.Linq;

namespace Batman.Cms.Services.Weixins
{
    public class WeixinMpAccountAppSvc : ServiceBase<OpenAccount>
    {
        public WeixinMpAccountAppSvc(IRepository<OpenAccount> repository, ToolBox toolBox) : base(repository, toolBox)
        {
        }

        public WeixinMpAccountDomainService WeixinMpAccountDomainService { get; set; }

        public ResponseBase Create(CreateWeixinMpAccountInput model)
        {
            var isUniqResult = WeixinMpAccountDomainService.IsUniq(model.AppId, model.ServiceNo);
            if (!isUniqResult.Success) return isUniqResult;

            var entity = ObjectMapper.Map<OpenAccount>(model);
            Repository.Insert(entity);

            return new ResponseBase(true);
        }

        public PagedResultDto<OpenAccount> GetWeixinMpAccounts(PagedResultRequestDto page, WeixinMpAccountFilter fitler)
        {
            var query = Repository.GetAll().AsNoTracking().Where(t => t.Platform == OpenAccountPlatform.微信);

            if (fitler.Status.HasValue)
            {
                query = query.Where(t => t.Status == fitler.Status.Value);
            }

            var total = query.Count();
            var data = query.OrderByDescending(t => t.Id).Skip(page.SkipCount).Take(page.MaxResultCount).ToList();

            return new PagedResultDto<OpenAccount>(total, data);
        }

        public ResponseBase Update(UpdateWeixinMpAccountInput model)
        {
            var isUniqResult = WeixinMpAccountDomainService.IsUniq(model.AppId, model.ServiceNo, model.Id);
            if (!isUniqResult.Success) return isUniqResult;

            var entity = Repository.GetAll().AsNoTracking().FirstOrDefault(t => t.Id == model.Id);
            if (entity == null)
            {
                return new ResponseBase(false, "当前编辑的公众号资料不存在，可能被临时删除了");
            }

            ObjectMapper.Map(model, entity);
            Repository.Update(entity);

            return new ResponseBase(true);
        }
    }
}
